﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class YaoWanLogin : LoginImplBase
    {
        public YaoWanLogin() : base(){ }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = "http://www.yaowan.com/?m=user&action=loginform&subdomain=as";
            string gamelisturl = "http://as.yaowan.com/as_server_list.html";
            // qaz55881801 : q123456
            string data = String.Format("username={0}&password={1}", _username , _password);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            string content = resp.getContent();
            if (content.IndexOf("alert") >= 0)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            // get url list
            findingServerUrl();
            if (_acc.ServerId == 391)
            {
                string red_url = "http://www.yaowan.com/?m=game&game_id=15&district_id=1157";
                processRedirect(red_url, result, ref cookies);
                return result;
            }
            
            resp = TransferMgr.doGetPure(gamelisturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetServerList; return result; }

            content = resp.getContent();

            // 查找serverid字符串
            //<a class="hover" target="_blank" href="http://www.yaowan.com/?m=game&game_id=15&district_id=7093">双线736区<span class="red">[最新]</span></a>
            //<a target="_blank" href="http://www.yaowan.com/?m=game&game_id=15&district_id=7092">双线735区</a>
            string district_name = _acc.ServerId == 500 ? "虎贲营" : String.Format("双线{0}区", _acc.ServerId);
            Regex re = new Regex(String.Format("<a.*href=\"([^\"']*?)\".*>{0}.*</a>", district_name));
            Match m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            string redirecturl = m.Groups[1].Value;

            processRedirect(redirecturl, result, ref cookies);
            return result;
        }
    }
}
